/**
 *
 *
 * 
 *
 * 
 */

package io.dbw.modules.business.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;

import io.dbw.common.exception.BusinessException;
import io.dbw.common.utils.PageUtils;
import io.dbw.common.utils.Query;
import io.dbw.modules.business.dao.SysConfigDao;
import io.dbw.modules.business.entity.SysConfigEntity;
import io.dbw.modules.business.service.SysConfigService;

@Service("sysConfigService")
public class SysConfigServiceImpl extends ServiceImpl<SysConfigDao, SysConfigEntity> implements SysConfigService {

	@Override
	public PageUtils<SysConfigEntity> queryPage(Map<String, Object> params) {
		String paramKey = (String)params.get("paramKey");

		IPage<SysConfigEntity> page = this.page(
			new Query<SysConfigEntity>().getPage(params),
			new QueryWrapper<SysConfigEntity>()
				.like(StringUtils.isNotBlank(paramKey),"param_key", paramKey)
				.eq("status", 1)
				.ne("param_type",0)
		);

		return new PageUtils(page);
	}

	@Override
	public void saveConfig(SysConfigEntity config) {
		this.save(config);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysConfigEntity config) {
		this.updateById(config);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateValueByKey(String key, String value) {
		baseMapper.updateValueByKey(key, value);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(List<Long> list) {
		this.removeByIds(list);
	}

	@Override
	public String getValue(String key) {
		SysConfigEntity config =baseMapper.queryByKey(key);

		return config == null ? null : config.getParamValue();
	}
	@Override
	public String getValue(String key,String sDef) {
		String value = getValue(key);
		if(StringUtils.isBlank(value)){
			return sDef;
		}
		return value;
	}

	@Override
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return new Gson().fromJson(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new BusinessException("获取参数失败");
		}
	}

	@Override
	public List<SysConfigEntity> getConfigListByParamType(Integer paramType) {
		return baseMapper.getConfigListByParamType(paramType);
	}
}
